package com.jblog.common.web.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import com.jblog.common.web.freemarker.exception.MustNotNullException;
import com.ocpsoft.pretty.time.PrettyTime;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
 * show pretty time like: <code>3 mins ago, 1 days ago</code>
 */
public class PrettyTimeDirective implements TemplateDirectiveModel {

    public static final String PARAM_DATE = "date";
    
    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        Date date = DirectiveUtils.getDate(PARAM_DATE, params);
        
        if (null == date) {
            throw new MustNotNullException(PARAM_DATE);
        } else {
            Writer out = env.getOut();
            PrettyTime p = new PrettyTime(new Locale(""));
            out.append(p.format(date));
        }
    }
    
    public enum Type {
        TEXT,
        HTML
    }

}
